package cast.it.zhang.phonenetwork;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import Uitls.LogUtil;
import Uitls.NetWorkUtils;
import Uitls.TrafficInfo;
import Uitls.TrafficUtils;

public class MainActivity extends AppCompatActivity implements Runnable {
    private Handler handler = new Handler();

    // 检测网速
    Handler mHandler;

    TrafficInfo speed;
    private WebView mWebView;
    private Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setAction("service.NetworkStateService");
        intent.setPackage("cast.it.zhang.phonenetwork");
        startService(intent);

        initTest();

        initWebView();

        trafficUse();//监测流量的使用情况

        jianceSpeed();// 网速
    }

    private void initTest() {
        bt = (Button) findViewById(R.id.bt_test);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NetWorkUtils net = new NetWorkUtils(MainActivity.this);
                boolean wifiConnected = net.isWifiConnected();
                LogUtil.d("connectInfo wifi 是否连接：", String.valueOf(wifiConnected));
                LogUtil.d("connectInfo mobile 是否连接：", String.valueOf(net.isMobileConnected()));
                LogUtil.d("connectInfo 连接的网络类型：", String.valueOf(net.getConnectedType()));
                LogUtil.d("connectInfo 网络运营商：", String.valueOf(net.getNetworkOperatorName()));
                LogUtil.d("connectInfo 是否是4G网络：", String.valueOf(net.is4G()));
                LogUtil.d("connectInfo 判断wifi是否打开：", String.valueOf(net.getWifiEnabled()));
                LogUtil.d("connectInfo 获取手机的ip地址 ：", net.getIpAddressString());
                LogUtil.d("connectInfo 获取域名的ip地址 ：", String.valueOf(net.getDomainAddress("netfits.io")));

            }
        });
    }

    private void initWebView() {
        mWebView = (WebView) findViewById(R.id.wv_news_detail);
        mWebView.loadUrl("http://www.baidu.com");
        WebSettings settings = mWebView.getSettings();
        settings.setBuiltInZoomControls(true);// 显示缩放按钮(wap网页不支持)
        settings.setUseWideViewPort(true);// 支持双击缩放(wap网页不支持)
        settings.setJavaScriptEnabled(true);// 支持js功能
        mWebView.setWebViewClient(new WebViewClient() {
            // 开始加载网页
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("开始加载网页了");
            }

            // 网页加载结束
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("网页加载结束");
            }

            // 所有链接跳转会走此方法
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("跳转链接:" + url);
                view.loadUrl(url);// 在跳转链接时强制在当前webview中加载

                //此方法还有其他应用场景, 比如写一个超链接<a href="tel:110">联系我们</a>, 当点击该超链接时,可以在此方法中获取链接地址tel:110, 解析该地址,获取电话号码, 然后跳转到本地打电话页面, 而不是加载网页, 从而实现了webView和本地代码的交互

                return true;
            }
        });
    }

    private void jianceSpeed() {
        final TextView speedTv = (TextView) findViewById(R.id.speed_tv);

        try {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 1) {
                        speedTv.setText(msg.obj + "kb/s");
                    }
                    super.handleMessage(msg);
                }

            };
            speed = new TrafficInfo(this,mHandler,getUid());
            speed.startCalculateNetSpeed(); // 开启网速监测
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("WrongConstant")
    public int getUid() {
        try {
            PackageManager pm = getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
            return ai.uid;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    private void trafficUse() {
        //1.获取一个包管理器。
        PackageManager pm = getPackageManager();
        //2.遍历手机操作系统 获取所有的应用程序的uid
        List<ApplicationInfo> appliactaionInfos = pm.getInstalledApplications(0);
        for (ApplicationInfo applicationInfo : appliactaionInfos) {
            int uid = applicationInfo.uid;    // 获得软件uid

            //proc/uid_stat/10086
            long tx = TrafficStats.getUidTxBytes(uid);//发送的 上传的流量byte
            long rx = TrafficStats.getUidRxBytes(uid);//下载的流量 byte
            //方法返回值 -1 代表的是应用程序没有产生流量 或者操作系统不支持流量统计
            LogUtil.d("flow 上传的流量byte : ",applicationInfo + " == " + String.valueOf(tx));
            LogUtil.d("flow 下载的流量byte : ",applicationInfo + " == " + String.valueOf(rx));
        }

        handler.postDelayed(this, 5000);// 打开定时器，执行操作
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(this);
        speed.stopCalculateNetSpeed();
    }

    @Override
    public void run() {
        long mobileTxBytes = TrafficStats.getMobileTxBytes();//获取手机3g/2g网络上传的总流量
        long mobileRxBytes = TrafficStats.getMobileRxBytes();//手机2g/3g下载的总流量
        String conversionWithUnitName = TrafficUtils.getConversionWithUnitNameForMonthly(mobileTxBytes);
        LogUtil.d("flow 3g/2g网络上传的总流量: ", conversionWithUnitName +"");
        String conversionWithUnitNameForMonthly = TrafficUtils.getConversionWithUnitNameForMonthly(mobileRxBytes);
        LogUtil.d("flow 2g/3g下载的总流量: ", conversionWithUnitNameForMonthly +"");

        long totalTxBytes = TrafficStats.getTotalTxBytes();//手机全部网络接口 包括wifi，3g、2g上传的总流量
        long totalRxBytes = TrafficStats.getTotalRxBytes();//手机全部网络接口 包括wifi，3g、2g下载的总流量
        String conversionWithUnitNameForMonthly1 = TrafficUtils.getConversionWithUnitNameForMonthly(totalTxBytes);
        LogUtil.d("flow wifi，3g、2g上传的总流量: ", conversionWithUnitNameForMonthly1+"");
        String conversionWithUnitNameForMonthly2 = TrafficUtils.getConversionWithUnitNameForMonthly(totalRxBytes);
        LogUtil.d("flow wifi，3g、2g下载的总流量: ", conversionWithUnitNameForMonthly2+"");
        handler.postDelayed(this,5000);
    }
}
